// 创建路由器
const express = require("express");
//引入连接池
const pool = require("../../pool");
//定义路由器
const router = express.Router();
//抛出路由器
module.exports = router;

router.get("/", (req, res) => {
  res.send({ info: "我是用户主页", code: 200 });
});

// 登录用户查询
router.post("/login", (req, res) => {
  let { username, password } = req.body;
  pool.query("SELECT * FROM xfn_reservation WHERE contactName=? and pwd=?", [username, password], (err, result) => {
    if (err) throw err;
    res.send(result[0]);
  });
});
// 请求侧边栏数据
router.get("/category", (req, res) => {
  pool.query("SELECT * FROM xfn_category ", (err, result) => {
    if (err) throw err;
    res.send(result);
  });
});

// 侧边栏对应菜单数据
router.get("/category/kinds", (req, res) => {
  let { id } = req.query;
  pool.query("SELECT * FROM xfn_dish WHERE categoryId=?", id, (err, result) => {
    if (err) throw err;
    res.send(result);
  });
});

// 菜品数量的修改
router.get("/category/numbers", (req, res) => {
  let { did, num, val, categoryId } = req.query;
  if (num < 0) {
    num = 0;
  }
  if (val >= 0) {
    num++;
  } else {
    num--;
  }
  pool.query("UPDATE xfn_dish SET num=? WHERE did=?", [num, did], (err, result) => {
    if (err) throw err;
    pool.query("SELECT * FROM xfn_dish WHERE categoryId=?", categoryId, (err, result) => {
      if (err) throw err;
      res.send(result);
    });
  });
});

// 总价计算
router.get("/category/total", (req, res) => {
  pool.query("SELECT * FROM xfn_dish ", (err, result) => {
    if (err) throw err;
    let total = result.reduce(function (prev, cur, index) {
      return prev + cur.price * cur.num;
    }, 0);
    res.send({ total });
  });
});

// 删除订单的选择
router.get("/category/delete", (req, res) => {
  pool.query("UPDATE xfn_dish SET num=? ", 0, (err, result) => {
    if (err) throw err;
    res.send("删除订单成功!");
  });
});
